package com.petRescueCenter.demo.voluntary.entity.DTO;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.petRescueCenter.demo.common.enumPackage.StateEmun;
import com.petRescueCenter.demo.voluntary.entity.Volunteer;

public class VolunteerQueryDTO {
	private Long userId;
	private String name;
	private String state;

	public Long getUserId() {
		return userId;
	}

	public String getName() {
		return name;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	@SuppressWarnings({ "serial" })
	public static Specification<Volunteer> getWhereClause(final VolunteerQueryDTO volunteerQueryDTO) {
		return new Specification<Volunteer>() {
			@Override
			public Predicate toPredicate(Root<Volunteer> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != volunteerQueryDTO.getUserId()) {
					predicate.add(criteriaBuilder.equal(root.get("id").as(Long.class), volunteerQueryDTO.getUserId()));
				}
				if (StringUtils.isNotBlank(volunteerQueryDTO.getState())) {
					/**
					 * REBACK("撤回"), APPROVING("审核中"), FALSE("失败"), SUCCESS("成功"), MAIL("已发邮");
					 */
					if (volunteerQueryDTO.getState().equals("0")) {
						predicate.add(criteriaBuilder.equal(root.get("state").as(StateEmun.class), StateEmun.REBACK));
					} else if (volunteerQueryDTO.getState().equals("1")) {
						predicate
								.add(criteriaBuilder.equal(root.get("state").as(StateEmun.class), StateEmun.APPROVING));
					} else if (volunteerQueryDTO.getState().equals("2")) {
						predicate.add(criteriaBuilder.equal(root.get("state").as(StateEmun.class), StateEmun.FALSE));
					} else if (volunteerQueryDTO.getState().equals("3")) {
						predicate.add(criteriaBuilder.equal(root.get("state").as(StateEmun.class), StateEmun.SUCCESS));
					} else {
						predicate.add(criteriaBuilder.equal(root.get("state").as(StateEmun.class), StateEmun.MAIL));
					}

				}

				if (StringUtils.isNotBlank(volunteerQueryDTO.getName())) {
					predicate.add(criteriaBuilder.like(root.get("name").as(String.class),
							"%" + volunteerQueryDTO.getName() + "%"));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		};
	}
}
